<script setup>
import { effect, onBeforeMount, ref } from 'vue';
import { updateNodeHandler } from '../../../api/node';
import { ElMessage } from 'element-plus';

const props = defineProps({
    // Noschedule NoExecute
  taintType: {
    type: String,
  },
  item: {
    type: Object,
  },
  clusterId: {
    type: String,
  },
})
const taint = ref(false)
onBeforeMount(() => {
    console.log("当前的污点类型和item的数据:",props.taintType,props.item)
    //判断当前节点是否已经配置了污点
    const taints = props.item.spec.taints
    if (taints != undefined){
        for (let i=0;i<taints.length;i++){
            const curTaint = taints[i]
            const effect = curTaint.effect
            const key = curTaint.key
            if (effect != props.taintType){
                continue
            }
            if (key == 'node-role.kubernetes.io/master' || 
                key == 'node-role.kubernetes.io/control-plane' || 
                key == 'node-role.kubernetes.io/controlplane'
            ) {
                taint.value = true
                break
            }
        }
    }
})
const updateTaint = () => {
    console.log("当前的值:",taint.value)
    //如果true: 去掉污点
    //如果false：添加污点
    if (taint.value){
        //去掉污点
        const taints = props.item.spec.taints
        for (let i=0;i<taints.length;i++){ 
            const curTaint = taints[i]
            const key = curTaint.key
            if (curTaint.effect == props.taintType){
                if (key == 'node-role.kubernetes.io/master' || 
                    key == 'node-role.kubernetes.io/control-plane' || 
                    key == 'node-role.kubernetes.io/controlplane'
            ){
                props.item.spec.taints.splice(i,1)
            }
            }
        }
        console.log("删除污点后的配置:",props.item.spec.taints)
    }else {
        const taint = {
            key: 'node-role.kubernetes.io/control-plane',
            effect: props.taintType,
        }
        if (props.item.spec.taints == undefined){
            props.item.spec.taints = []
        }
        props.item.spec.taints.push(taint)
    }
    //更新节点的状态
    return new Promise(async (resolve, reject) => {
       await updateNodeHandler(props.clusterId, props.item.metadata.name, props.item)
       .then((res) => {
           if (res.data.status == 200){
            ElMessage.success(res.data.message)
            return resolve(true)
           }else {
            ElMessage.error(res.data.message)
            return reject(false)
           }
        }).catch(() => {
            err =>{
                ElMessage.error(err.message)
                return reject(false)
            }
        })
    })
}
</script>

<template>
    <el-switch v-model="taint" :before-change="updateTaint"></el-switch>
</template>

<style scoped>

</style>
